using System.Collections.Generic;
using System.Linq;
using System.Web;
using Foothill.Model;
using Foothill.Service.MiscInfo;
using Foothill.Service.VehicleInfo;
using Foothill.Service.Exceptions;

namespace Foothill.Service.Caching
{
    // update this collection everytime add a new session
    public static class ApplicationDataNames
    {
        public static readonly string VehicleCondition = "VehicleCondition";
        public static readonly string ListingType = "ListingType";
        public static readonly string TransmissionType = "TransmissionType";
        public static readonly string Cities = "Cities";
    }

    public class LocalCache : System.Web.UI.Page, ILocalCache
    {
        private IVehicleInfoService _vehicleInfoService;
        private IMiscInfoService _miscInfoService;
        
        public LocalCache(IVehicleInfoService service, IMiscInfoService miscInfoService) 
        {
            _vehicleInfoService = service;
            _miscInfoService = miscInfoService;
        }

        public void Refresh()
        {
            try
            {
                HttpContext.Current.Application[ApplicationDataNames.VehicleCondition] = _vehicleInfoService.GetVehicleConditions();
                HttpContext.Current.Application[ApplicationDataNames.ListingType] = _vehicleInfoService.GetListingTypes();
                HttpContext.Current.Application[ApplicationDataNames.TransmissionType] = _vehicleInfoService.GetTransmissionTypes();
                HttpContext.Current.Application[ApplicationDataNames.Cities] = _miscInfoService.GetCities((int)Provinces.BC);
            }
            catch (ServiceException exception)
            {
                throw new LocalCacheException("Error in refreshing local data cache", exception);
            }
        }

        public IDictionary<int, string> GetLocalApplicationDataDict(string appDataName)
        {
            IDictionary<int, string> dict = null;

            if (HttpContext.Current.Application.AllKeys.Contains(appDataName))
            {
                dict = HttpContext.Current.Application[appDataName] as Dictionary<int, string>;
            }

            return (dict) ?? new Dictionary<int, string>();
        }

        public string GetStringValue(string appDataName, int key)
        {
            string retVal = "";
            IDictionary<int, string> dict = GetLocalApplicationDataDict( appDataName );

            if (dict.Count > 0)
            {
                retVal = dict.FirstOrDefault( p => p.Key == key ).Value;
            }

            return retVal;
        }
    }
}
